﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Frame.Lib.Enums;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Frame.Lib.Common;

namespace Frame.Lib.Utilities
{
    /// <summary>
    /// 常用JS类集合
    /// </summary>
    public sealed class JSUtil
    {

        private static Page page
        {
            get
            {
                return (Page)System.Web.HttpContext.Current.CurrentHandler;
            }
        }

        #region 脚本提示
        /// <summary>
        /// 脚本提示
        /// </summary>
        /// <param name="p_strMessage"></param>
        /// <returns></returns>
        public static void Alert(string strMessage)
        {
            string strScript = "alert('" + strMessage.Replace("'", "\"") + "');";

            page.ClientScript.RegisterStartupScript(page.GetType(), "message", strScript, true);
        }
        #endregion

        /// <summary>
        /// 包含一段脚本文件
        /// </summary>
        /// <param name="key"></param>
        /// <param name="url"></param>
        public static void IncludeJS(string key, string url)
        {
            page.ClientScript.RegisterClientScriptInclude(key, url);
        }

        #region 执行脚本
        /// <summary>
        /// 执行脚本
        /// </summary>
        /// <param name="page"></param>
        /// <param name="strScript"></param>
        public static void ExcuteJS(string strScript)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "jsAction", strScript, true);
        }

        /// <summary>
        /// 执行脚本,用于同一页执行多个脚本，带key
        /// </summary>
        /// <param name="page"></param>
        /// <param name="strScript"></param>
        /// <param name="key"></param>
        public static void ExcuteJS(string strScript, string key)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), key, strScript, true);
        }
        #endregion

        #region 设置页面自适应的div的高度
        /// <summary>
        /// 设置页面自适应的div的高度,让些高度正好撑满页面
        /// </summary>
        /// <param name="dest">容器div的id</param>
        /// <param name="usedHeight">已经用掉的高度</param>
        public static void SetDivHeight(string dest, int usedHeight)
        {
            HtmlGenericControl body = null;
            if (page.Master != null)
            {
                body = (HtmlGenericControl)page.Master.Page.Form.FindControl("body");
            }
            else
            {
                body = (HtmlGenericControl)page.Form.FindControl("body");
            }
            if (body == null)
            {
                throw new Exception("缺少服务器端的body");
            }

            body.Attributes.Add("onload", "setDivHeight('" + dest + "'," + usedHeight + ")");
        }

        /// <summary>
        /// 设置页面自适应的div的高度,并参考里面table的高度
        /// </summary>
        /// <param name="dest">容器div的id</param>
        /// <param name="usedHeight">已经用掉的高度</param>
        public static void SetTableHeight(string dest, int usedHeight)
        {
            HtmlGenericControl body = null;
            if (page.Master != null)
            {
                body = (HtmlGenericControl)page.Master.Page.Form.FindControl("body");
            }
            else
            {
                body = (HtmlGenericControl)page.Form.FindControl("body");
            }

            if (body == null)
            {
                throw new Exception("缺少服务器端的body");
            }

            body.Attributes.Add("onload", "setTableHeight('" + dest + "'," + usedHeight + ")");
        }
        #endregion

        #region 刷新页面的GridView
        /// <summary>
        /// 刷新页面的GridView,一般用于弹出页保存后的刷新
        /// </summary>
        /// <param name="page"></param>
        /// <param name="strRefreshButton"></param>
        public static void RefreshView()
        {
            string strScript = "top.refreshView(false);top.delDivFrm();";
            ResponseJS(strScript);
        }

        public static string GetDelFrmString()
        {
            return "top.delDivFrm();";
        }

        /// <summary>
        /// 用于保存后并继续添加
        /// </summary>
        /// <param name="page"></param>
        public static void RefreshView(System.Web.UI.Page page)
        {
            string strScript = "parent.refreshView(true);";
            ExcuteJS(strScript, "refresh");
        }
        #endregion

        #region 返回JS，中断页面输出
        /// <summary>
        /// 返回JS，中断页面输出
        /// </summary>
        /// <param name="strScript"></param>
        public static void ResponseJS(string strScript)
        {
            try
            {
                page.Response.Write("<script type='text/javascript'>" + strScript + "</script>");
                page.Response.End();
            }
            catch { }
        }
        #endregion


        #region 弹出div对话框
        /// <summary>
        /// 弹出div对话框
        /// </summary>
        /// <param name="button">加onclick事件的按钮，可为null</param>
        /// <param name="title">标题</param>
        /// <param name="titleImg">标题图片</param>
        /// <param name="url">对话框的Url</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns>创建div对话框的js脚本，可以给客户端更加灵活的使用</returns>
        public static string ShowForm(IAttributeAccessor button, string title, string titleImg, string url, int width, int height)
        {
            if (titleImg == null)
            {
                titleImg = "null";
            }
            if (!url.StartsWith("/"))
            {
                url = GlobalVar.WebCurrPath + url;
            }
            string str = "return CreateDivFrm(\"" + System.Web.HttpUtility.UrlEncode(title) + "\"," + titleImg + ",\"" + url + "\"," + width + "," + height + ")";
            if (button != null)
            {
                if (button is HyperLink)
                {
                    ((HyperLink)button).NavigateUrl = "javascript:;";
                }
                button.SetAttribute("onclick", str);
            }
            return str;
        }
        #endregion

        #region 选择左边二、三级菜单的某一个模块，用于服务器端控制客户端的选择
        /// <summary>
        /// 选择左边二、三级菜单的某一个模块，用于服务器端控制客户端的选择
        /// </summary>
        /// <param name="moduleID">模块的ID</param>
        /// <param name="message">在跳转之前弹出的提示信息，可以空</param>
        public static void SelectModule(int moduleID, string message)
        {
            string script = "top.selectModule('" + moduleID + "');";
            if (message != null && message != "")
            {
                script = "alert('" + message + "');" + script;
            }

            page.Response.Write("<script type='text/javascript'>" + script + "</script>");

            try
            {
                page.Response.End();
            }
            catch
            { }
        }
        #endregion

        #region 给超链接加上服务器器按钮的单击事件
        /// <summary>
        /// 给超链接加上服务器器按钮的单击事件
        /// </summary>
        /// <param name="src">加事件的对象，只要有Attributes属性的都可以，一般是超链接</param>
        /// <param name="button">服务器端按钮</param>
        public static void ClickBtn(System.Web.UI.IAttributeAccessor src, System.Web.UI.Control button)
        {
            if (src is HtmlAnchor)
            {
                ((HtmlAnchor)src).HRef = "javascript:ClickBtn('" + button.ClientID + "')";
            }
            else if (src is HyperLink)
            {
                ((HyperLink)src).NavigateUrl = "javascript:ClickBtn('" + button.ClientID + "')";
            }
            else
            {
                src.SetAttribute("onclick", "ClickBtn('" + button.ClientID + "')");
            }
        }
        #endregion

        #region 批量删除时的js确认
        /// <summary>
        /// 批量删除时的js确认
        /// </summary>
        /// <param name="button">删除按钮</param>
        /// <param name="title">删除确认信息</param>
        public static void DelConfirm(System.Web.UI.IAttributeAccessor button, string title)
        {
            System.Web.UI.WebControls.HiddenField hidSelectIDs = (System.Web.UI.WebControls.HiddenField)page.FindControl("hidSelectIDs");
            if (hidSelectIDs == null)
            {
                hidSelectIDs = (HiddenField)page.Master.FindControl("ContentPlaceHolder1").FindControl("hidSelectIDs");
            }
            DelConfirm(button, title, hidSelectIDs);
        }

        /// <summary>
        /// 批量删除时的js确认
        /// </summary>
        /// <param name="button">删除按钮</param>
        /// <param name="title">删除确认信息</param>
        /// <param name="hidSelectIDs">放被删除ID的字符串的Hidden</param>
        private static void DelConfirm(System.Web.UI.IAttributeAccessor button, string title, System.Web.UI.WebControls.HiddenField hidSelectIDs)
        {
            button.SetAttribute("onclick", "return delConfirm(" + hidSelectIDs.ClientID + ",'" + title + "')");
        }
        #endregion

        #region 弹出通用树状对话框
        /// <summary>
        /// 弹出通用树状对话框
        /// </summary>
        /// <param name="hidID">放ID的Hidden</param>
        /// <param name="txtName">放Name的TextBox,单击可弹出对话框</param>
        /// <param name="tableName">TableName枚举</param>
        /// <param name="title">标题</param>
        /// <param name="singleSelect">是否为单选</param>
        public static void ShowTreeDlg(System.Web.UI.WebControls.HiddenField hidID, System.Web.UI.WebControls.TextBox txtName, string tableName, string title, bool singleSelect)
        {
            ShowTreeDlg(hidID, txtName, tableName, title, singleSelect, null);
        }

        /// <summary>
        /// 弹出通用树状对话框
        /// </summary>
        /// <param name="hidID">放ID的Hidden</param>
        /// <param name="txtName">放Name的TextBox,单击可弹出对话框</param>
        /// <param name="tableName">TableName枚举</param>
        /// <param name="title">标题</param>
        /// <param name="singleSelect">是否为单选</param>
        /// <param name="button">单击此按钮可弹出对话框</param>
        public static void ShowTreeDlg(System.Web.UI.WebControls.HiddenField hidID, System.Web.UI.WebControls.TextBox txtName, string tableName, string title, bool singleSelect, IAttributeAccessor button)
        {
            string url = GlobalVar.WebAppPath + "Common/Dialog/TreeDlg.aspx";
            txtName.Style.Add("cursor", "pointer");
            txtName.Attributes.Add("readonly", "readonly");
            txtName.Attributes.Add("onclick", "showTree(" + hidID.ClientID + "," + txtName.ClientID + ",'" + url + "','" + tableName + "','" + page.Server.UrlEncode(title) + "'," + singleSelect.ToString().ToLower() + ")");
            if (button != null)
            {
                button.SetAttribute("onclick", "showTree(" + hidID.ClientID + "," + txtName.ClientID + ",'" + url + "','" + tableName + "','" + page.Server.UrlEncode(title) + "'," + singleSelect.ToString().ToLower() + ")");
            }
        }
        #endregion

        /// <summary>
        /// 弹出一普通的对话框
        /// </summary>
        /// <param name="UserIDs"></param>
        /// <param name="UserNames"></param>
        /// <param name="p"></param>
        public static string ShowDlg(HiddenField hidID, TextBox txtName, string url)
        {
            return ShowDlg(hidID, txtName, url, null);
        }

        public static string ShowDlg(HiddenField hidID, TextBox txtName, string url, IAttributeAccessor button)
        {
            txtName.Style.Add("cursor", "pointer");
            txtName.Attributes.Add("readonly", "readonly");
            string script = "showDialog('" + hidID.ClientID + "','" + txtName.ClientID + "','" + url + "');";
            txtName.Attributes.Add("onclick", script);
            txtName.ToolTip = "单击进行选择";
            if (button != null)
            {
                button.SetAttribute("onclick", script);
            }
            return script;
        }
        #region 弹出部门用户的对话框

        /// <summary>
        /// 弹出部门用户的对话框
        /// </summary>
        /// <param name="hidID">放ID的Hidden</param>
        /// <param name="txtName">放Name的TextBox,单击可弹出对话框</param>
        /// <param name="singleSelect">是否为单选</param>
        public static void ShowDeptUserTreeDlg(System.Web.UI.WebControls.HiddenField hidID, System.Web.UI.WebControls.TextBox txtName, bool singleSelect, bool? allowCheckDept)
        {
            ShowDeptUserTreeDlg(hidID, txtName, singleSelect, allowCheckDept, null);
        }

        /// <summary>
        /// 弹出部门用户的对话框
        /// </summary>
        /// <param name="hidID">放ID的Hidden</param>
        /// <param name="txtName">放Name的TextBox,单击可弹出对话框</param>
        /// <param name="singleSelect">是否为单选</param>
        /// <param name="button">单击此按钮可弹出对话框</param>
        public static string ShowDeptUserTreeDlg(System.Web.UI.WebControls.HiddenField hidID, System.Web.UI.WebControls.TextBox txtName, bool singleSelect, bool? allowChekcDept, IAttributeAccessor button)
        {
            txtName.Style.Add("cursor", "pointer");

            txtName.Attributes.Add("readonly", "readonly");
            string script = "showDeptUserTree(" + hidID.ClientID + "," + txtName.ClientID + "," + singleSelect.ToString().ToLower();
            if (allowChekcDept != null)
            {
                script += "," + allowChekcDept.ToString().ToLower();
            }
            script += ")";
            txtName.Attributes.Add("onclick", script);
            if (button != null)
            {
                button.SetAttribute("onclick", script);
            }
            return script;
        }
        #endregion

        #region 选择多个用户，部门用于辅助选择而不保存部门
        /// <summary>
        /// 选择多个用户，部门用于辅助选择而不保存部门 
        /// </summary>
        /// <param name="InnerMemberIDs"></param>
        /// <param name="InnerMembers"></param>
        public static string ShowDeptUserTreeEx(HiddenField hidID, TextBox txtName)
        {
            return ShowDeptUserTreeEx(hidID, txtName, null);
        }


        public static string ShowDeptUserTreeEx(HiddenField hidID, TextBox txtName, IAttributeAccessor button)
        {
            txtName.Style.Add("cursor", "pointer");

            txtName.Attributes.Add("readonly", "readonly");
            string script = "showDeptUserTreeEx('" + hidID.ClientID + "','" + txtName.ClientID + "')";
            txtName.Attributes.Add("onclick", script);
            if (button != null)
            {
                button.SetAttribute("onclick", script);
            }
            return script;
        }
        #endregion

        #region 为左边插入三级模块
        /// <summary>
        /// 为左边插入三级模块
        /// </summary>
        /// <param name="moduleID"></param>
        /// <param name="html"></param>
        /// <param name="isUpdate">如果isUpdate为true，则就替换老的</param>
        public static void AddModule3(int moduleID, string html, bool isUpdate)
        {
            string strScript = "top.addModule3(" + moduleID + ",\"" + html + "\"," + isUpdate.ToString().ToLower() + ");";
            ExcuteJS(strScript, moduleID.ToString());
        }
        #endregion

        /// <summary>
        /// 返回弹出对话框的值
        /// </summary>
        /// <param name="values"></param>
        /// <param name="texts"></param>
        public static void ReturnDlgValue(string values, string texts)
        {
            StringBuilder sbJS = new StringBuilder();
            sbJS.Append("<script language='javascript'>\n");
            sbJS.Append("var args=window.dialogArguments;");
            sbJS.Append("args[0]=\"" + values + "\";\n");
            sbJS.Append("args[1]=\"" + texts + "\";\n");
            sbJS.Append("window.close();\n");
            sbJS.Append("</script>");

            page.Response.Write(sbJS.ToString());
            try
            {
                page.Response.End();
            }
            catch
            { }

        }

        public static void CloseDialog(string msg)
        {
            StringBuilder sbJS = new StringBuilder();
            sbJS.Append("<script language='javascript'>\n");
            if (msg != null && msg != "")
            {
                sbJS.Append("alert('" + msg + "');");
            }
            sbJS.Append("window.close();\n");

            sbJS.Append("</script>");

            page.Response.Write(sbJS.ToString());
            try
            {
                page.Response.End();
            }
            catch
            { }
        }

        /// <summary>
        /// 对一个树状目录进行移动
        /// </summary>
        /// <param name="btnMove"></param>
        /// <param name="tableName"></param>
        /// <param name="hidSelectIDs"></param>
        /// <param name="btnRefresh"></param>
        public static void MoveTree(IAttributeAccessor btnMove, string tableName, HiddenField hidSelectIDs, Button btnRefresh)
        {
            btnMove.SetAttribute("onclick", "return moveDir('" + GlobalVar.WebAppPath + "Common/Dialog/MoveTree.aspx?TableName=" + tableName + "&','" + hidSelectIDs.ClientID + "'," + btnRefresh.ClientID + ")");
        }

        public static void SetTreeSelect(List<int> lstRestoreIDs)
        {
            if (lstRestoreIDs != null && lstRestoreIDs.Count > 0)
            {
                string str = StrUtil.MergeToStr(lstRestoreIDs, ",");
                string script = "restoreTreeSelect('" + str + "')";

                ExcuteJS(script, "SetTreeSelect");
            }
        }
    }
}
